package com.chen.solution.springboot.thymeleaf.demo.controller;

import com.chen.solution.springboot.thymeleaf.demo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.UUID;

/**
 * <p>desc: </p>
 *
 * @author chentian
 * @date 2022/2/27
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/userForm")
    public ModelAndView userForm(){
        ModelAndView mav = new ModelAndView("userForm");
        User user = new User();
        mav.addObject("user", user);
        return mav;
    }

    @PostMapping("/addUser")
    public String addUser(@Valid User user, BindingResult bindingResult, RedirectAttributes attr){
        // 请求参数验证
        if(bindingResult.hasErrors()){
            return "userForm";
        }

        //TODO 持久化操作
        user.setId(UUID.randomUUID().toString());
        log.info("user:{}", user.toString());

        // 使用 attr 传递参数,暂存在 session ； redirect 防止重复提交
        attr.addFlashAttribute("user", user);
        return "redirect:/user/userInfo";
    }

    @GetMapping("/userInfo")
    public String userInfo(){
        return "userInfo";
    }

}
